<script lang="ts" setup>
import type { FavoriteVO } from '#/api/company/favorite/model';

import { onMounted, ref, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { Select } from 'ant-design-vue';

import { favoriteList } from '#/api/company/favorite';

interface Props {
  getFavoriteList?: boolean; // 是否通过接口获取收藏夹列表，默认是
  favorites?: FavoriteVO[]; // 动态传入收藏夹列表，一般用于不通过接口查询时
  mode?: 'multiple' | 'tags' | undefined;
  allowClear?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  getFavoriteList: true,
  favorites: () => [],
  mode: undefined,
  allowClear: false,
});

const emit = defineEmits(['blur', 'change']);
const selectMode = ref(props.mode);
const isLoaded = ref(false);
const options = ref<FavoriteVO[]>([]);
const selected = defineModel<number | number[] | string | string[]>('value', {
  default: () => undefined,
});

watch(
  () => props.favorites,
  () => {
    options.value = props.favorites;
  },
);

onMounted(async () => {
  if (props.getFavoriteList) {
    if (!isLoaded.value) {
      const list = await favoriteList();
      options.value = list.map((v) => {
        // v.disabled = v.status === '1';
        return v;
      });
      isLoaded.value = true;
    }
  } else {
    options.value = props.favorites;
  }
});

function onChange() {
  emit('change', selected.value);
}
</script>
<template>
  <Select
    v-model:value="selected"
    class="w-full"
    placeholder="请选择"
    :allow-clear="allowClear"
    show-search
    :mode="selectMode"
    :class="{ 'valid-success': !!selected }"
    :options="options"
    option-filter-prop="name"
    :field-names="{ label: 'name', value: 'id' }"
    @blur="emit('blur')"
    @change="onChange"
  >
    <template #option="{ name }">
      <div class="flex items-center">
        <span class="mr-[5px] text-yellow-500">
          <IconifyIcon icon="mdi:folder-favorite" />
        </span>
        {{ name }}
      </div>
    </template>
  </Select>
</template>
